package models

import (
	"fmt"
	"sync"
	"time"

	"github.com/axgle/mahonia"
)

var (
	昨天      []byte
	今天      []byte
	明天      []byte
	日期      = 0 //
	日期_lock sync.RWMutex
)

//获取KEY
func GetKey(ret []byte, step int) {
	if 日期 != time.Now().Day() {
		fmt.Println("开始生成加密串数组")
		日期_lock.Lock()
		tm := time.Now()
		tm = tm.Add(time.Hour * -24)
		s := fmt.Sprintf("%d年%d月%d日", tm.Year(), tm.Month(), tm.Day())
		昨天 = GetPassword(s)

		tm = tm.Add(time.Hour * 24)
		s = fmt.Sprintf("%d年%d月%d日", tm.Year(), tm.Month(), tm.Day())
		今天 = GetPassword(s)

		tm = tm.Add(time.Hour * 24)
		s = fmt.Sprintf("%d年%d月%d日", tm.Year(), tm.Month(), tm.Day())
		明天 = GetPassword(s)

		日期 = time.Now().Day()
		日期_lock.Unlock()
	}
	日期_lock.RLock()
	switch step {
	case 0:
		copy(ret, 今天)
	case 1:
		copy(ret, 昨天)
	case 2:
		copy(ret, 明天)
	}
	日期_lock.RUnlock()
}
func GetPassword(s string) []byte {
	ret := make([]byte, 256)
	bys := []byte(mahonia.NewEncoder("gbk").ConvertString(s)) //编码转换
	tmlen := len(bys)                                         //获取长度
	var temp1, temp2, temp3, temp4 byte
	for i := 0; i < 256; i++ {
		ret[i] = byte(i)
	}
	for i := 0; i < 256; i++ {
		temp1 = bys[i%tmlen]          //秘钥
		temp2 = ret[i]                //key
		temp3 = temp1 + temp3 + temp2 //计算偏移值
		temp4 = ret[temp3]            //读取偏移后数据

		ret[i] = temp4
		ret[temp3] = temp2
	}
	return ret
}

//解码
func Password(KEY []byte, buff []byte, start int, 掩码 uint32) uint32 { //加解密函数 调用这个即可 数组指针 长度
	var temp1, temp2, temp3, temp4 byte
	temp4 = byte(掩码)
	掩码 >>= 8
	temp3 = byte(掩码)
	掩码 >>= 8
	temp2 = byte(掩码)
	掩码 >>= 8
	temp1 = byte(掩码)

	for i := start; i < len(buff); i++ {
		temp1 = KEY[(i+1)%256]
		temp3 = temp1 + temp3 //保存变量
		temp2 = KEY[temp3]

		KEY[(i+1)%256] = temp2
		KEY[temp3] = temp1

		temp2 = temp1 + temp2
		temp1 = KEY[temp2]
		temp4 = buff[i]
		temp4 = temp4 ^ temp1
		buff[i] = temp4
	}
	掩码 = uint32(temp1)
	掩码 <<= 8
	掩码 |= uint32(temp2)
	掩码 <<= 8
	掩码 |= uint32(temp3)
	掩码 <<= 8
	掩码 |= uint32(temp4)
	return 掩码
}
